package cc.linker.steplink.crm.merchant.service.impl;

import cc.linker.steplink.crm.merchant.dao.FreightAreaDao;
import cc.linker.steplink.crm.merchant.dao.FreightTemplateDao;
import cc.linker.steplink.crm.merchant.pojo.FreightTemplatePo;
import cc.linker.steplink.crm.merchant.service.redis.FreightTemplateRedisService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Author: CKQ
 * @DateTime: 2020/6/23 17:05
 * @Description: TODO
 */
@Service
public class FreightTemplateRedisServiceImpl implements FreightTemplateRedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private FreightTemplateDao freightTemplateDao;
    @Autowired
    private FreightAreaDao freightAreaDao;

    public String FREIGHT_TEMPLATE_KEY = "sys_config:freightTemplate_";

    @Async
    @Override
    public void setFreightTemplateRedis(String templateId) {
        if (stringRedisTemplate.opsForValue().size(FREIGHT_TEMPLATE_KEY + templateId) == 0) {
            FreightTemplatePo po = freightTemplateDao.getFreightTemplateModel(templateId);
            po.freightAreaPos = freightAreaDao.getFreightAreaList(po.templateId);
            stringRedisTemplate.opsForValue().set(FREIGHT_TEMPLATE_KEY + templateId, JSON.toJSONString(po));
        }
    }

    @Async
    @Override
    public void deleteFreightTemplateRedis(String templateId) {
        stringRedisTemplate.delete(FREIGHT_TEMPLATE_KEY + templateId);
    }

    //获取运费模板
    @Override
    public FreightTemplatePo getFreightTemplateRedis(String templateId) {
        String freightTemplateStr = stringRedisTemplate.opsForValue().get(FREIGHT_TEMPLATE_KEY + templateId);
        if (StringUtils.isEmpty(freightTemplateStr)) {
            return freightTemplateDao.getFreightTemplateModel(templateId);
        } else {
            return JSON.parseObject(freightTemplateStr, FreightTemplatePo.class);
        }
    }
}
